package com.mingyizhudao.app.view.recommend;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.dixiang.framework.common.QJNetUICallback;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.http.DataHandler;
import com.dixiang.framework.utils.Utils;
import com.dixiang.framework.widget.LoadingDialog;
import com.dixiang.framework.widget.PullToRefreshView;
import com.dixiang.framework.widget.PullToRefreshView.OnFooterRefreshListener;
import com.dixiang.framework.widget.PullToRefreshView.OnHeaderRefreshListener;
import com.google.gson.reflect.TypeToken;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.entity.CityEntity;
import com.mingyizhudao.app.entity.HospitalEntity;
import com.mingyizhudao.app.entity.ProvinceEntity;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.IntentHelper;
import com.mingyizhudao.app.view.MYApplication;
import com.mingyizhudao.app.view.MYBaseFragment;
import com.mingyizhudao.app.view.MainActivity;
import com.mingyizhudao.app.view.recommend.adapter.CityListAdapter;
import com.mingyizhudao.app.view.recommend.adapter.HospitalListAdapter;
import com.mingyizhudao.app.view.recommend.bean.HospitalEntityView;

public class RecommendFragment extends MYBaseFragment {

	private Context context;
	private LayoutInflater mInflater;
	private PullToRefreshView refresh_lv_hospital;
	private ListView mActual_lv_hospital;
	private HospitalListAdapter hospitalListAdapter;
	private List<HospitalEntity> hospitalList;
	private HospitalEntityView hospitalEntityView;
	private int page = 1;
	private List<ProvinceEntity> listProvince;
	private String cityId = "1";
	private String cityName = "北京";

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
					Bundle savedInstanceState) {
		View mView = inflater.inflate(R.layout.fragment_recommend, container,
						false);
		initView(mView);
		loadInitData();
		return mView;
	}

	@Override
	public void initHeaderView() {
		clearTitle();
		setTitleViewValue(0, 0, R.color.white);
		setTitleViewValue("推荐医院");
		setTopViewBg(R.color.actionbar_bg_color);
		initOptionView( R.drawable.location_icon, 0, new  OnClickListener() {
			@Override
			public void onClick(View v) {
				if (listProvince != null && listProvince.size() > 0) {
					initCityPopupWindow(v, context);
				} else {
					Toast.makeText(context, "数据加载未完成！", 0).show();
				}
			}
		});
		
	}


	private void initCityPopupWindow(View v, Context context) {
		// 设置pop窗口的视图，用布局转换器将xml转换成view
		View contentView = mInflater.inflate(R.layout.pop_province_city, null);
		// 获得pop窗口，设置大小(宽高设置为填充)，ViewGroup.LayoutParams.MATCH_PARENT填充父类
		PopupWindow pop = new PopupWindow(
						contentView,
						LayoutParams.MATCH_PARENT,
						(int) (MYApplication.heightPixels - (MYApplication.startheight + ((43+50) * MYApplication.density))));
		RadioGroup rg_province = (RadioGroup) contentView
						.findViewById(R.id.rg_province);
		ListView lv_city = (ListView) contentView.findViewById(R.id.lv_city);

		List<CityEntity> cityList = new ArrayList<CityEntity>();
		CityListAdapter cityListAdapter = new CityListAdapter(context, cityList);
		lv_city.setAdapter(cityListAdapter);
		setCityDate(pop, rg_province, cityListAdapter, lv_city, cityList);

		// 获得焦点
		pop.setFocusable(true);
		pop.setBackgroundDrawable(new BitmapDrawable());// 点击完按钮后另其消失（方法：设置一个空的bitmap）
		// 设置pop窗口显示的位置
		// 将按钮和pop窗口关联上，v表示一个显示的基点(按钮的基点为左下点)
		pop.showAtLocation(
						v,
						Gravity.TOP,
						0,
						(int) (MYApplication.startheight + (43 * MYApplication.density)));
		pop.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {

			}
		});

	}

	/**
	 * 设置添加屏幕的背景透明度
	 * 
	 * @param bgAlpha
	 */
	public void backgroundAlpha(float bgAlpha) {
		WindowManager.LayoutParams lp = getActivity().getWindow()
						.getAttributes();
		lp.alpha = bgAlpha; // 0.0-1.0
		getActivity().getWindow().setAttributes(lp);
	}


	private void getCityDate() {
		String url = Constants.baseURL + "city"; //+ Constants.basePARAM;//+ "&api=4"
		QJNetUICallback callback = new QJNetUICallback<QjResult<List<ProvinceEntity>>>(activity) {
			@Override
			public void onSuccess(QjResult<List<ProvinceEntity>> result) {
				if( result!=null )
				{
					listProvince = result.getResults();
				}
			}

			public void onError(Exception e, QjResult<List<ProvinceEntity>> result) {
			};

			public void onCompleted(Exception e, QjResult<List<ProvinceEntity>> result) {
				super.onCompleted(e, result);
			};
		};
		String path = new DataHandler().getDataObject(activity, url,null, new TypeToken<QjResult<List<ProvinceEntity>>>() {}, callback);
	}

	private void setCityDate(final PopupWindow pop,
					final RadioGroup rg_province,
					final CityListAdapter cityListAdapter, final ListView lv_city,
					final List<CityEntity> cityList) {

		if (listProvince != null && listProvince.size() > 0) {
			for (int i = 0; i < listProvince.size(); i++) {
				RadioButton rb = (RadioButton) mInflater.inflate(
								R.layout.province_radio_btn, null);
				rb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
								(int) (45 * MYApplication.density)));
				rb.setId(i);
				rb.setText(listProvince.get(i).getState());
				if (i == 0) {
					rb.setChecked(true);
					cityList.clear();
					cityList.addAll(listProvince.get(i).getSubCity());
					cityListAdapter.notifyDataSetChanged();
				}
				rg_province.addView(rb);
			}

			rg_province
			.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(RadioGroup group,
								int checkedId) {
					cityList.clear();
					cityList.addAll(listProvince.get(checkedId)
									.getSubCity());
					cityListAdapter.notifyDataSetChanged();
				}
			});

			lv_city.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
								int position, long arg3) {
					page = 1;
					cityName = cityList.get(position).getCity();
					
					((MainActivity)activity).setRightText( cityName ,R.color.white);
					
					cityId = "" + cityList.get(position).getId();
					getHospitalDate(true);
					if (pop.isShowing()) {
						pop.dismiss();
					}
				}

			});

		} else {
			Toast.makeText(context, "数据加载失败！", 0).show();
		}
	}

	private void initView(View mView) {
		context = getActivity();
		mInflater = LayoutInflater.from(context);

		refresh_lv_hospital = (PullToRefreshView) mView
						.findViewById(R.id.refresh_lv_hospital);
		mActual_lv_hospital = (ListView) mView
						.findViewById(R.id.mActual_lv_hospital);

		// 获取头部控件
		View headerView = activity.getLayoutInflater().inflate(R.layout.fg_recommend_hostital_header, null);
		mActual_lv_hospital.addHeaderView(headerView, false, false);
		
		((MainActivity)activity).setRightText( cityName ,R.color.white);

		refresh_lv_hospital
		.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {

			@Override
			public void onHeaderRefresh(PullToRefreshView refreshView) {
				// 刷新不加载更多
				page = 1;
				getHospitalDate(true);
			}
		});

		refresh_lv_hospital
		.setOnFooterRefreshListener(new OnFooterRefreshListener() {

			@Override
			public void onFooterRefresh(PullToRefreshView refreshView) {
				// 加载更多
				page++;
				getHospitalDate(false);
			}
		});

		mActual_lv_hospital.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
				if(hospitalList == null) return;
				// Intent intent = new Intent( context,
				// HospitalToDeptActivity.class );
				Bundle bundle = new Bundle();
				HospitalEntity hospitalEntity = hospitalList.get(position-1);
				bundle.putSerializable("hospitalEntity", hospitalEntity);
				bundle.putSerializable("hospitalViewUrl",
								hospitalEntityView == null ? "" : hospitalEntityView.getHospitalViewUrl());
				// intent.putExtras( bundle );
				// startActivity( intent );
				IntentHelper.getInstance(getActivity()).gotoActivity(
								HospitalToDeptActivity.class, bundle);
			}

		});
	}

	public void getHospitalDate(final boolean isFresh) {
		String url = Constants.baseURL + "appnav3" + "?city=" + cityId + "&page=" + page;//&api=4
		
		LoadingDialog.getInstance(activity).show();
		QJNetUICallback callback = new QJNetUICallback<QjResult<HospitalEntityView>>(activity) {
			@Override
			public void onSuccess(QjResult<HospitalEntityView> result) {
				try {
					if (result != null) {
						hospitalEntityView = result.getResults();

						List<HospitalEntity> list = hospitalEntityView
										.getHospitals();
						if (list == null
										|| (list != null && list.size() <= 0)) {
							Toast.makeText(context, "没有更多数据！", 0).show();
							if (isFresh) {
								if(hospitalList != null) hospitalList.clear();
								hospitalListAdapter.notifyDataSetChanged();
							}
						} else {
							if (isFresh) {
								Constants.IS__HOSPITAL_NEAD_REFRESH = false;
								Utils.saveDataToCache(RecommendFragment.class.getSimpleName(), list);
								hospitalList.clear();
							}
							hospitalList.addAll(list);
							hospitalListAdapter.notifyDataSetChanged();
						}
					}

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			public void onError(Exception e, QjResult<HospitalEntityView> result) {
				super.onError(e, result);
			};

			public void onCompleted(Exception e, QjResult<HospitalEntityView> result) {
				super.onCompleted(e, result);
				refresh_lv_hospital.onHeaderRefreshComplete();
				refresh_lv_hospital.onFooterRefreshComplete();
			};
		};
		String path = new DataHandler().getDataObject(activity, url,null, new TypeToken<QjResult<HospitalEntityView>>() {}, callback);
	}

	private void loadInitData(){
		try{
			if (hospitalListAdapter == null || hospitalListAdapter.isEmpty() || Constants.IS__HOSPITAL_NEAD_REFRESH) {
				try{	
					List<HospitalEntity> list = (List<HospitalEntity>)Utils.getDataFromCache(RecommendFragment.class.getSimpleName());
					hospitalList = new ArrayList<HospitalEntity>();
					if(list != null && list.size() > 0){
						hospitalList.addAll(list);
					}
				}catch(Exception ex){
					ex.printStackTrace();
				}
				hospitalListAdapter = new HospitalListAdapter(context, hospitalList);
				getHospitalDate(true);
			}
			if (listProvince == null || listProvince.size() == 0) {
				getCityDate();
			}
			mActual_lv_hospital.setAdapter(hospitalListAdapter);
		}catch(Exception ex){
			ex.printStackTrace();
		}


	}

}
